//
//  SWOauthController.swift
//  MYSwiftWeiBo
//
//  Created by shingwai chan on 16/2/28.
//  Copyright © 2016年 ChanShingWai. All rights reserved.
//

import UIKit
//import SVProgressHUD

class SWOauthController: UIViewController  {

    override func loadView() {
        self.view = webView
        webView.delegate =  self
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpNavigationBar()
        
        let request = NSURLRequest(URL: SWNetWorkTool.sharedNetWorkTool.oAuthLoginURL())

        webView.loadRequest(request)
    }
    
    //设置navigationBar
    func setUpNavigationBar() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fill")
    
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    
    
    func fill() {
        
//        let me =     "document.getElementById('userId').value='czbkiosweibo@163.com';document.getElementById('passwd').value='czbkios008'"
        
        let me  = "document.getElementById('userId').value='keepert@163.com';document.getElementById('passwd').value='Rr758941'"
        
        webView.stringByEvaluatingJavaScriptFromString(me)
        
    }
    
    func close() {
//        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    // MARK:-----懒加载
    lazy var webView: UIWebView = UIWebView()
}

//MARK: ----- UIWebViewDelegate
extension SWOauthController :UIWebViewDelegate {
    
    //开始请求时调用
    func webViewDidStartLoad(webView: UIWebView) {
        
//        SVProgressHUD.showWithStatus("正在加载登陆页面", maskType: SVProgressHUDMaskType.Black)
    }

    //完成加载时调用
    func webViewDidFinishLoad(webView: UIWebView) {
//        SVProgressHUD.dismiss()
    }
    
    //失败时调用
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        if error?.code != 102 {
//            SVProgressHUD.showErrorWithStatus("加载失败", maskType: SVProgressHUDMaskType.Gradient)
        }
    }
    
    //询问是否加载某个请求 true:请求 false:不请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        
        let urlString = request.URL?.absoluteString
        print("urlString = \(urlString)")
        
        // 1.判断是否是回调地址开头.是回调地址开头,表示点击的是授权或取消按钮
        if urlString!.hasPrefix(SWNetWorkTool.sharedNetWorkTool.redirect_uri)
        {
            
            let query = request.URL?.query
            print("query = \(query)")
            
            //如果query返回的是code=开头的就是授权按钮
            let codeString = "code="
            if (query!.hasPrefix(codeString))
            {
                //授权按钮 获取code的值
                let queryNS = query! as NSString
                let code = queryNS.substringFromIndex(codeString.characters.count)
                print("code = \(code)")
                
                //用viewModel 向新浪发送code 获取Token 当成功或错误的时候都会回调用闭包 assTockenfinishedCallBack
                SWUserAccountViewModel.sharedInstance.loadAccessToken(code, assTockenfinishedCallBack: { (error) -> () in
                    //当不能获取Token的时候
                    if error != nil {
                        print("获取token失败\(error)")
//                        SVProgressHUD.showErrorWithStatus("网络不给力", maskType: SVProgressHUDMaskType.Black)
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            //获取不到token 回到主页面
                            self.close()
                        })
                        //跳出闭包 回到viewModel
                        return
                    }
                    //来到这就证明已经获取了Token并且存起来了
//                    SVProgressHUD.showSuccessWithStatus("登陆成功",maskType: SVProgressHUDMaskType.Black)
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                        //登陆成功 到欢迎界面
                        self.close()
                        AppDelegate.outSideChoeseRootViewController(false)
                    })
                })//获取token完成
                
            } else {
                //按了取消
                close()
            }//取消就不发送请求 因为请求的是回调地址
            return false
            
        } else //发送请求 就不是授权也不是取消
        {
            return true
        }
    }
}
